//
//  CXComposeController.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/26.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import SVProgressHUD


let CXComposePictureMargin: CGFloat = 10

class CXComposeController: UIViewController {

    /// 是否让工具条动画 默认为true
    private var tbIsAni: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        
        //添加监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //添加监听表情按键按下的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionBtnDidClick:", name: CXEmoBtnDidClickNotification, object: nil)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    /// 右边的实际按钮
    private lazy var rightButton: UIButton = {
        
        let button = UIButton()
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        //添加点击事件 发送微博
        button.addTarget(self, action: "sendClick", forControlEvents: .TouchUpInside)
        //Disable状态下按钮的字体颜色
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.frame.size = CGSize(width: 45, height: 30)
        return button
    }()
    /// 标题区域自定义
    private lazy var titleView: UILabel = {
        
        let tv = UILabel()
        tv.textAlignment = .Center
        tv.numberOfLines = 2

        if let nameStr = CXUserInfoViewModel.sharedUserModel.userInfo?.screen_name {
            
            let script = "发微博\n\(nameStr)"
            let textBuilder = NSMutableAttributedString(string: script)
            let scriptRange = (script as NSString).rangeOfString(nameStr)
            textBuilder.addAttributes([NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(15)], range: scriptRange)
            tv.attributedText = textBuilder
            tv.sizeToFit()  //别忘了尺寸
        }
        return tv
    }()
    /// 文字输入显示区域
    private lazy var textview: CXTextView = {
       
        let textV = CXTextView()
        textV.placeholder = "啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"
        textV.delegate = self
        textV.font = UIFont.systemFontOfSize(16)
        return textV
    }()
    @available(iOS 9.0, *)
    /// 工具条
    private lazy var toolBar: CXStackView = {
        let tb = CXStackView(frame: CGRectZero)
        tb.delegate = self
        return tb
    }()
    /// 图片显示view
    private lazy var pictureView: CXPictureView = {
        
        let pictureV = CXPictureView()
        pictureV.hidden = true
        pictureV.addPicBlock = {[weak self] in
            
            self?.popPictureController()
        }
        return pictureV
    }()
    /// 表情键盘view
    private lazy var emotionKeyboard: CXEmotionKeyboard = {
        
        let keyboard = CXEmotionKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 226)
        return keyboard
    }()
}
// MARK: - 进行UI设置
extension CXComposeController: UITextViewDelegate {
    ///  在滚动的时候收回键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "goBack")
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false //让右按钮不可用
        
        //设置textView
        view.addSubview(textview)
        if #available(iOS 9.0, *) {
            view.addSubview(toolBar)
        } else {
            // Fallback on earlier versions
        }
        //图片视图可以随着text视图滚动
        textview.addSubview(pictureView)
        
        textview.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textview).offset(100)
            make.leading.equalTo(textview).offset(CXComposePictureMargin)
//            make.trailing.equalTo(textview).offset(-CXComposePictureMargin)
            //需要这么操作
            make.height.width.equalTo(textview.snp_width).offset(-2 * CXComposePictureMargin)
        }
    }
    
    @objc private func goBack() {
        //在界面消失之前保证键盘先消失
        view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    ///  监听键盘frame改变
    @objc private func keyboardWillChangeFrame(noti: NSNotification) {
        
        if !tbIsAni {
            return
        }
        
        let endframe = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue() //获取键盘的最终frame
        let aniduration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue //获取键盘动画的持续时间
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endframe.origin.y - view.frame.height)
        }
        
        UIView.animateWithDuration(aniduration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    ///  监听表情按钮按下
    @objc private func emotionBtnDidClick(noti: NSNotification) {
//        print(noti.userInfo)  是之前发送通知传入的字典
        let emotionInfo = noti.userInfo!["emotion"] as! CXEmotion
        textview.insertEmotion(emotionInfo)
    }
    ///  发送按钮
    @objc private func sendClick() {
        
        /*
        发送微博 有两种情况：文本加图片、纯文本
        */
        //可以通过pictureView的 pictures 属性来判断是否含有图片
        if pictureView.pictures.count > 0 {
            //文本图片混编发送
            sendMixMsg()
        } else {
            //纯文本发送
            sendPureText()
        }
    }
    //涉及到一个图文混排处理 将这个处理过程封装到 UITextView的分类中去
    //包含文本信息和图片
    private func sendMixMsg() {

        let image = pictureView.pictures.first!
        
        CXNetworkTool.sharedTool.upload(image: image, accessToken: CXUserInfoViewModel.sharedUserModel.userInfo!.access_token!, status: textview.emotionText) { (response, error) -> Void in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送微博失败")
            } else {
                SVProgressHUD.showSuccessWithStatus("发送微博成功")
            }
        }
    }
    ///  发送纯文本信息 包含表情
    private func sendPureText() {
        // 发送文字微博
        CXNetworkTool.sharedTool.sendStatus(puretext: textview.emotionText, accessToken: CXUserInfoViewModel.sharedUserModel.userInfo!.access_token!) { (response, error) -> Void in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送微博文本失败")
            } else {
                SVProgressHUD.showSuccessWithStatus("发送微博文本成功")
            }
        }
    }
    ///  当在屏幕里向里面敲字的时候 监听,然后调整发送按钮的可用状态
    func textViewDidChange(textView: UITextView) {
        //测试
//        print(NSStringFromCGRect(textview.frame))  打印的frame是完整屏幕大小 位置是0，0
        //由于有导航栏 因此被做了特殊处理
//        print(NSStringFromCGPoint(textView.contentOffset)) //被做了特殊处理 移动了64
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
// MARK: - 遵守工具条点击协议 负责工具条按钮的弹出控制器操作
extension CXComposeController: CXToolBarDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func composeBarButtonDidClick(type: CXToolButtonType) {
        //TODO: 如果type是图片，则弹出图片选择框
        switch type {
        case .Picture:
            popPictureController()
        case .Mention:
            print("提及")
        case .Trend:
            print("趋势")
        case .Emotion:
//            print("表情")
            switchKeyboardE()
        case .Add:
            print("添加")
        }
    }
    ///  弹出图片选择框
    private func popPictureController() {
        
        let picController = UIImagePickerController()
//        picController.sourceType = .PhotoLibrary
        picController.delegate = self
        presentViewController(picController, animated: true, completion: nil)
    }
    ///  弹出表情键盘
    private func switchKeyboardE() {
        
        //inputview默认为nil，即系统键盘。否则为自定义键盘
        textview.inputView = (textview.inputView == nil) ? emotionKeyboard : nil
        toolBar.isSystemKB = textview.inputView == nil
        
        tbIsAni = false      //注销再成为第一响应者才能改变键盘；注销的时候不进行动画，防止抖动发生
        textview.resignFirstResponder()
        tbIsAni = true
        textview.becomeFirstResponder()
    }
    
    
    ///  实现图片选择控制器的代理方法
    //一点实现了系统的代理方法 某些功能系统不会再帮我们完成 需要我们手动调用
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //addPicutre(image)
        //dismissViewControllerAnimated(true, completion: nil)
        pictureView.addPicture(image.thinnerPicTo(width: 400))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
